package com.huatai.datacenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.util.CollectionUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import com.huatai.datacenter.config.CustomDataModelException;
import com.huatai.datacenter.entity.datamodel.DataModelApplyEntity;
import com.huatai.datacenter.entity.datamodel.DataModelBaseEntity;
import com.huatai.datacenter.entity.datamodel.DataModelEntity;
import com.huatai.datacenter.entity.datamodel.DataModelFieldEntity;
import com.huatai.datacenter.mapper.DataModelMapper;
import com.huatai.datacenter.service.DataModelApplyService;
import com.huatai.datacenter.service.DataModelFieldService;
import com.huatai.datacenter.service.DataModelService;
import com.huatai.datacenter.utils.DataModelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gusiyi
 * @version 1.0
 * @className DataModelServiceImpl
 * @description 描述：数据模型service实现类
 * @date 2023/5/25 17:11
 */
@Service
public class DataModelServiceImpl extends ServiceImpl<DataModelMapper,DataModelEntity> implements DataModelService {

	@Autowired
	private DataModelFieldService dataModelFieldService;
	@Autowired
	private DataModelApplyService dataModelApplyService;

	@Override
	public Page<DataModelEntity> selectDataModelList(DataModelEntity dataModelEntity) {
		LambdaQueryWrapper<DataModelEntity> dataModelQuery = Wrappers.lambdaQuery();
		dataModelQuery
			.eq(DataModelBaseEntity::getDeleted,false)
			.like(StringUtil.isNotBlank(dataModelEntity.getDataModelName()),DataModelEntity::getDataModelName,dataModelEntity.getDataModelName())
			.eq(ObjectUtil.isNotEmpty(dataModelEntity.getDataModelTypeId()),DataModelEntity::getDataModelTypeId,dataModelEntity.getDataModelTypeId())
			.orderByDesc(DataModelBaseEntity::getUpdateTime);
		Page<DataModelEntity> page = new Page<>(dataModelEntity.getPageIndex(),dataModelEntity.getPageSize());
		Page<DataModelEntity> dataModelEntityPage = page(page, dataModelQuery);
		for (DataModelEntity recordData : dataModelEntityPage.getRecords()) {
			List<DataModelFieldEntity> dataModelFieldEntities = dataModelFieldService.getDataModelFieldList(recordData.getId());
			recordData.setFields(dataModelFieldEntities);
		}
		return dataModelEntityPage;
	}

	@Override
	@Transactional(rollbackFor = {Exception.class})
	public boolean insertDataModel(DataModelEntity dataModelEntity) {
		boolean save = save(dataModelEntity);
		List<DataModelFieldEntity> fields = dataModelEntity.getFields();
		if(CollectionUtil.isNotEmpty(fields)){
			for (DataModelFieldEntity field : fields) {
				field.setDataModelId(dataModelEntity.getId());
			}
			dataModelFieldService.saveBatch(fields);
		}
		return save;
	}

	@Override
	@Transactional(rollbackFor = {Exception.class})
	public boolean updateDataModel(DataModelEntity dataModelEntity) {
		List<DataModelFieldEntity> fields = dataModelEntity.getFields();
		List<Long> fieldIds = new ArrayList<>(fields.size());
		for (DataModelFieldEntity field : fields) {
			field.setDataModelId(dataModelEntity.getId());
			fieldIds.add(field.getId());
		}
		LambdaQueryWrapper<DataModelFieldEntity> fieldEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
		fieldEntityLambdaQueryWrapper
			.eq(DataModelFieldEntity::getDeleted,false)
			.eq(DataModelFieldEntity::getDataModelId,dataModelEntity.getId())
			.notIn(DataModelFieldEntity::getId,fieldIds);
		DataModelFieldEntity dataModelFieldEntity = new DataModelFieldEntity();
		dataModelFieldEntity.setDeleted(true);
		dataModelFieldService.update(dataModelFieldEntity,fieldEntityLambdaQueryWrapper);
		dataModelFieldService.saveOrUpdateBatch(dataModelEntity.getFields());
		return updateById(dataModelEntity);
	}

	@Override
	@Transactional(rollbackFor = {Exception.class})
	public boolean deleteByIds(List<DataModelEntity> dataModelEntitys) {
		List<DataModelEntity> deleteDataModelList = new ArrayList<>(dataModelEntitys.size());
		StringBuilder resultMsg = new StringBuilder();
		boolean deleteFlag = false;
		List<Long> deleteFields = new ArrayList<>(dataModelEntitys.size());
		for (DataModelEntity dataModelEntity : dataModelEntitys) {
			LambdaQueryWrapper<DataModelApplyEntity> applyQuery = Wrappers.lambdaQuery();
			applyQuery
				.eq(DataModelApplyEntity::getDeleted,false)
				.eq(DataModelApplyEntity::getDataModelId,dataModelEntity.getId());
			long hasDataModelApplyUsed = dataModelApplyService.count(applyQuery);
			if (hasDataModelApplyUsed>0){
				List<DataModelApplyEntity> dataModelApplyEntities = dataModelApplyService.list(applyQuery);
				resultMsg.append(DataModelUtil.getDeleteFailedMsg("模型管理",dataModelApplyEntities.get(0).getDataModelName(),"模型应用管理",
					()->{
						StringBuilder msg = new StringBuilder();
						for (DataModelApplyEntity dataModelApplyEntity : dataModelApplyEntities) {
							msg.append("\"")
								.append(dataModelApplyEntity.getApplyName())
								.append("\",");
						}
						return msg.substring(0,msg.length()-1);
					}));
				deleteFlag = true;
			}else {
				dataModelEntity.setDeleted(true);
				deleteDataModelList.add(dataModelEntity);
				deleteFields.add(dataModelEntity.getId());
			}
		}
		if (deleteFlag) {
			resultMsg.append("请先在模型应用管理中修改或删除以上模型应用后再进行模型删除。");
			throw new CustomDataModelException(resultMsg.toString());
		}
		DataModelFieldEntity deleteField = new DataModelFieldEntity();
		deleteField.setDeleted(true);
		updateBatchById(deleteDataModelList);
		LambdaQueryWrapper<DataModelFieldEntity> deleteFieldQuery = Wrappers.lambdaQuery();
		deleteFieldQuery
			.in(DataModelFieldEntity::getDataModelId,deleteFields);
		return dataModelFieldService.update(deleteField,deleteFieldQuery);
	}
}
